package com.bite.book.interceptor;

import com.bite.book.constant.Constants;
import com.bite.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2025-06-05
 * Time:21:11
 */
//拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor preHandle...");
        //true 放行， false 拦截
        //获取session，并判断session中存储的userinfo信息是否为空
        HttpSession session = request.getSession();//从上面的request中获取
        UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);//获取用户信息
        //判断是否为空
        if(userInfo==null||userInfo.getId()<=0){
            //用户未登录
            response.setStatus(401);//设置为401,未经过认证--不能访问
            return false;
        }
        return true;//不为空，则可以通行
    }

}
